import axios, { AxiosPromise, AxiosRequestConfig, AxiosInstance } from "axios"
import { message } from 'ant-design-vue'
import useToken from "@/hooks/token/useToken"
const server = axios.create({
    baseURL: "/api"
})

const source = axios.CancelToken.source()

const { checkExpire, TOKEN } = useToken()
server.interceptors.request.use(config => {
    if (checkExpire() && !config.url?.includes("auth")) {
        source.cancel("token过期了")
        location.href = "/login"
    }

    config.headers['Authorization'] = `Bearer ${TOKEN.token}`
    return config
})

server.interceptors.response.use(
    response => {
        return response.data || []
    },
    err => {
        if (err.response.status == 403) {
            source.cancel("token过期了")
            location.href = "/login"
        }
    }
)



class MyAxiosRequest {
    request: AxiosInstance
    path: string | undefined//备份的初始配文件
    requestOptions: AxiosRequestConfig

    constructor(request: AxiosInstance, requestOptions: AxiosRequestConfig) {
        this.request = request
        this.requestOptions = { ...requestOptions }
        this.path = requestOptions.url
    }

    //设置params
    setParams(params: Record<string, unknown>) {
        this.requestOptions.params = params
        return this
    }

    //设置data参数
    setData(data: Record<string, unknown>) {
        this.requestOptions.data = data
        return this
    }

    //设置URL 
    setEndPath(url: string) {
        this.requestOptions.url = this.path?.endsWith('/') ? `${this.path}${url}` : `${this.path}/${url}`
        return this
    }

    //错误提示
    _Msg(response: any) {
        response.then((res: any) => {
            if (typeof res != 'object') return
            if (res.code == 0) {
                message.success(res.msg, 1)
                message.success("执行成功,请手动返回上级页面", 3)

            } else {
                message.error(res.msg, 5)
            }
        })

    }

    //重新请求
    /**
     * @param msg 是否自动弹出处理结果
     * @param callback 请求之后的处理
    */
    reload(msg = false, callback?: Function) {
        const response = this.request(this.requestOptions)
        if (msg) {
            this._Msg(response)
        }
        callback && callback(response)
        return response
    }
}

export function useService(config: AxiosRequestConfig): MyAxiosRequest {
    if (!config) {
        throw new Error("配置文件不能为空")
    }
    return new MyAxiosRequest(server, config)
}



declare interface TokenReac {
    token: string;
    expire: string;
}
